<?php


namespace Wunder\Esorm;

use phpDocumentor\Reflection\Types\String_;
use Swoft\Bean\Annotation\Mapping\Bean;
use Wunder\Esorm\Connection\Connection;
use Wunder\Esorm\Connection\ConnectionManager;
use Swoft\Bean\BeanFactory;
use Wunder\Esorm\Eloquent\Builder;
use Wunder\Esorm\Exception\EormException;
use Wunder\Esorm\Connection\BeanTest;
use Wunder\Esorm\Handler\Collection;

/**
 * Class Esorm
 *
 * @method static Builder|Collection index(string $index)
 * @method static Builder|Collection query(string $index="")
 * @method static array get(array $source = [])
 * @method static array find($id="")
 * @method static Builder|Collection sort(array $sorts)
 * @method static Builder|Collection size(int $size)
 * @method static Builder|Collection form(int $form)
 * @method static Builder|Collection paginate(int $page, int $size)
 * @method static Builder|Collection source(array $source)
 *
 * @package Wunder\Esorm
 */
class Esorm
{
    /**
     * connection
     *
     * @param string $pool
     *
     * @return Connection
     * @throws EormException
     */
    public static function connection(string $pool = Pool::DEFAULT_POOL): Connection
    {
        try {
            /* @var ConnectionManager $conManager */
            $conManager = BeanFactory::getBean(ConnectionManager::class);

            /* @var Pool $eormPool */
            $eormPool  = bean($pool);
            $connection = $eormPool->getConnection();

            $connection->setRelease(true);
            $conManager->setConnection($connection);

        } catch (Exception $e) {
            throw new EormException(
                sprintf('Pool error is %s file=%s line=%d', $e->getMessage(), $e->getFile(), $e->getLine())
            );
        }

        return $connection;
    }

    /**
     * __callStatic
     *
     * @param $name
     * @param $arguments
     *
     * @return mixed
     * @throws ElasticsearchException
     */
    public static function __callStatic($name, $arguments)
    {
        /** @var Connection $instance */
        $instance = self::connection();

        return $instance->collection->$name(...$arguments);
    }
}
